package com.ks.common;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestDataGengertor {

    private static final String SERVER_URL = "http://localhost:8000/api/metric/put"; // 服务器URL
//    private static final String SERVER_URL = "http://120.92.110.170:8001/api/metric/put"; // 服务器URL


    public static void main(String[] args) {
        try {
            sendLocalData("C:\\Users\\knight\\Desktop\\tim\\test2.json");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void sendPostRequest(String data) throws IOException {
        URL url = new URL(SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream outputStream = connection.getOutputStream();
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))) {
            writer.write(data);
            writer.flush();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("Data sent successfully.");
            } else {
                System.out.println("Failed to send data. Response code: " + responseCode);
            }
        }
    }


    private static void sendLocalData(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("File does not exist.");
            return;
        }
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        }
        sendPostRequest(content.toString());
    }



}
